package game.test.client;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Game extends JPanel implements Runnable {
	private static final int width = 800;
	private static final int height = 600;

	public boolean running = false;
	public Random random = new Random();

	private Thread gameThread;

	private Network client;
	private String name;

	private Graphics g;
	private BufferedImage buffer;
	
	private int cState = 1;
	private int ticks = 0;

	private void init() {
		buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		g = buffer.getGraphics();
	}

	private void connect() {
		name = String.valueOf(random.nextInt(10000));
		client = new Network(this);
		client.setServerProperties("localhost", -1);
		if (!client.connect()) {
			client.disconnect();
			cState = 3;
		} else {
			cState = 2;
		}

		client.startListening();
		client.send(Network.CLIENT_INFO + Network.DATA_SEPARATOR + name);
	}

	private void update() {
		if (ticks == 1) {
			connect();
		}
		ticks++;
	}

	private void render() {
		g.setColor(Color.BLACK);
		g.fillRect(0, 0, width, height);
		
		g.setColor(Color.WHITE);
		if (cState == 1) {
			g.drawString("Connecting to the server...", 10, 20);
		} else if (cState == 2) {
			g.drawString("Connected!", 10, 20);
		} else if (cState == 3) {
			g.drawString("Failed to connect to the server! " + client.reason, 10, 20);
		}
		
		this.getGraphics().drawImage(buffer, 0, 0, width, height, null);
	}

	public void run() {
		init();
		while (running) {
			update();
			render();
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void start() {
		running = true;
		gameThread = new Thread(this);
		gameThread.start();
	}

	private void stop() {
		running = false;
		try {
			gameThread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Game game = new Game();

		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(false);
		frame.setSize(width, height);
		frame.add(game);
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);

		game.start();
	}
}